package com.example.demo.aop;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-31
 * Time: 20:07
 */
//定义切面
@Component
@Aspect //定义切面 类的名字不能是Aspect
public class UserAspect {

    //定义切点 切点的方法中没有具体实现 (设置拦截规则)
    @Pointcut("execution(* com.example.demo.controller.UserController.*(..))")
    public void pointcut(){}

    //实现通知
    @Before("pointcut()")
    public void doBefore(){
        System.out.println("执行了前置Before方法!");
    }

    @After("pointcut()")
    public void doAfter(){
        System.out.println("执行了后置After方法!");
    }
    @After("pointcut()")
    public void doAfter1(){
        System.out.println("++++++++++============+++++++++");
    }


    @AfterReturning("pointcut()")
    public void doAfterReturning(){
        System.out.println("执行了return之后执行的方法!");
    }

    @AfterThrowing("pointcut()")
    public void doAfterThrowing(){
        System.out.println("执行了出现异常之后执行的方法!");
    }

    @Around("pointcut()")
    //环绕通知 固定写法
    public Object doAround(ProceedingJoinPoint joinPoint){
        Object result = null;
        System.out.println("环绕通知的前置方法 在before之前");
        try {
            joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("环绕通知的后置方法 在after之后");
        return result;
    }

    //可以存在多个 但是相同通知之间也存在先后
    @Around("pointcut()")
    public Object doA(ProceedingJoinPoint joinPoint){
        Object result = null;
        System.out.println("哈哈哈哈哈哈哈哈哈哈哈");
        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();
            result = joinPoint.proceed();
            stopWatch.stop();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("方法的执行时间" + stopWatch.getTotalTimeMillis());
        return result;
    }

}
